<template>
  <div class="p-2">
    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-form-item label="分类名称" class="smart-query-form-item">
          <a-input v-model:value="queryParams.categoryName" placeholder="请输入分类名称" />
        </a-form-item>
        <a-form-item label="分类编码" class="smart-query-form-item">
          <a-input v-model:value="queryParams.code" placeholder="请输入分类编码" />
        </a-form-item>
        <a-form-item class="smart-query-form-item smart-margin-left10">
          <a-button-group>
            <a-button type="primary" @click="handleQuery">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="resetQuery">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </a-button-group>
        </a-form-item>
      </a-row>
    </a-form>

    <a-card size="small" :bordered="false">
      <a-row class="smart-table-btn-block">
        <div class="smart-table-operate-block">
          <a-button type="primary" @click="handleAdd">
            <template #icon><PlusOutlined /></template>
            新增
          </a-button>

          <a-button @click="handleExport()">
            <template #icon><DownloadOutlined /></template>
            导出
          </a-button>
        </div>
      </a-row>

      <a-table :loading="loading" :columns="columns" :dataSource="categoryList" :pagination="false" bordered>
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'action'">
            <a-space>
              <a-button type="link" @click="handleUpdate(record)">
                <template #icon><EditOutlined /></template>
                修改
              </a-button>
              <a-button type="link" danger @click="handleDelete(record)">
                <template #icon><DeleteOutlined /></template>
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>

      <div class="smart-query-table-page">
        <a-pagination
          v-show="total > 0"
          :total="total"
          v-model:current="queryParams.pageNum"
          v-model:pageSize="queryParams.pageSize"
          @change="getList"
          showSizeChanger
          showQuickJumper
        />
      </div>
    </a-card>

    <!-- 添加或修改参数配置对话框 -->
    <a-modal :title="dialog.title" v-model:open="dialog.visible" width="500px">
      <a-form ref="categoryFormRef" :model="form" :rules="rules" :label-col="{ span: 4 }">
        <a-form-item label="分类名称" name="categoryName">
          <a-input v-model:value="form.categoryName" placeholder="请输入分类名称" />
        </a-form-item>
        <a-form-item label="分类编码" name="code">
          <a-input v-model:value="form.code" placeholder="请输入分类编码" />
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="form.remark" placeholder="请输入内容" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button type="primary" @click="submitForm">确 定</a-button>
        <a-button @click="cancel">取 消</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup name="Category">
  import { categoryApi } from '/@/api/workflow/category';
  import { message, Modal } from 'ant-design-vue';
  import { SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined, DeleteOutlined, DownloadOutlined } from '@ant-design/icons-vue';

  const { proxy } = getCurrentInstance();

  const categoryList = ref([]);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);

  const queryFormRef = ref(null);
  const categoryFormRef = ref(null);
  const dialog = reactive({
    visible: false,
    title: '',
  });

  const initFormData = {
    categoryId: undefined,
    categoryName: '',
    code: '',
    remark: '',
  };

  const data = reactive({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      categoryName: '',
      code: '',
    },
    rules: {
      categoryName: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
      code: [{ required: true, message: '分类编码不能为空', trigger: 'blur' }],
    },
  });

  const { queryParams, form, rules } = toRefs(data);

  const columns = ref([
    {
      title: '分类编号',
      dataIndex: 'categoryId',
      align: 'center',
    },
    {
      title: '分类名称',
      dataIndex: 'categoryName',
      align: 'center',
    },
    {
      title: '分类编码',
      dataIndex: 'code',
      align: 'center',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      width: 200,
    },
  ]);

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      ids.value = selectedRowKeys;
      single.value = selectedRowKeys.length !== 1;
      multiple.value = !selectedRowKeys.length;
    },
  };

  /** 查询参数列表 */
  const getList = async () => {
    loading.value = true;
    try {
      const { data } = await categoryApi.listCategory(queryParams.value);
      categoryList.value = data.list;
      total.value = data.total;
    } finally {
      loading.value = false;
    }
  };

  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  };

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    categoryFormRef.value?.resetFields();
  };

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  };

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  };

  /** 新增按钮操作 */
  const handleAdd = () => {
    dialog.visible = true;
    dialog.title = '添加分类';
    nextTick(() => {
      reset();
    });
  };

  /** 修改按钮操作 */
  const handleUpdate = (row) => {
    dialog.visible = true;
    dialog.title = '修改分类';
    const categoryId = row?.categoryId || ids.value[0];
    nextTick(async () => {
      reset();
      const { data } = await categoryApi.getCategory(categoryId);
      form.value = data;
    });
  };

  /** 提交按钮 */
  const submitForm = async () => {
    try {
      await categoryFormRef.value.validate();
      if (form.value.categoryId) {
        await categoryApi.updateCategory(form.value);
      } else {
        await categoryApi.addCategory(form.value);
      }
      message.success('操作成功');
      dialog.visible = false;
      getList();
    } catch (error) {
      console.error('表单验证失败', error);
    }
  };

  /** 删除按钮操作 */
  const handleDelete = async (row) => {
    const categoryIds = row?.categoryId || ids.value;
    Modal.confirm({
      title: '确认删除',
      content: `是否确认删除参数编号为"${categoryIds}"的数据项？`,
      onOk: async () => {
        await categoryApi.delCategory(categoryIds);
        getList();
        message.success('删除成功');
      },
    });
  };

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download(
      'workflow/category/export',
      {
        ...queryParams.value,
      },
      `category_${new Date().getTime()}.xlsx`
    );
  };

  onMounted(() => {
    getList();
  });
</script>
